const hx = require("hbuilderx");
const MessageHandler = require('./messageHandler.js')

function registerCommands(context){
	try{
		let openUcoder = hx.commands.registerCommand('ucoder.openUcoder',async ()=>{
			hx.window.showView({
			  viewId: 'extension.ucoderWebView',
			});
		})
		let explainCode = hx.commands.registerCommand('ucoder.explainCode',async ()=>{
			let content = await getCode()
			postMessage('explainCode',content)
		})
		context.subscriptions.push(explainCode)
		let optimizeCode = hx.commands.registerCommand('ucoder.optimizeCode',async ()=>{
			let content = await getCode()
			postMessage('optimizeCode',content)
		})
		context.subscriptions.push(optimizeCode)
		let commentCode = hx.commands.registerCommand('ucoder.commentCode',async ()=>{
			let content = await getCode()
			postMessage('commentCode',content)
		})
		context.subscriptions.push(commentCode)
		
	}catch(err){
		console.log('注册命令错误',err)
	}
	
}

function postMessage(command, data) {
		const instance = MessageHandler.getInstance();
		if (instance) {
			instance.postMessage({
				command,
				data
			});
		}
	}
	
async function getCode(){
	let textData = ''
	try {
		const activeTextEditor = await hx.window.getActiveTextEditor()
		if (!activeTextEditor) {
			console.warn('没有活动的文本编辑器');
			textData = ''
		}
		activeTextEditor.edit((editBuilder => {
			const selection = activeTextEditor.selection;
			const document = activeTextEditor.document
			// 获取选中的内容
			textData = document.getText(selection)
		}));
	} catch (error) {
		console.error('错误:', error);
		textData = ''
	}
	return textData
}

module.exports = {
	registerCommands
}